import os

def delete_pyc_files(root_dir):
    deleted_count = 0
    for dirpath, dirnames, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename.endswith('.pyc'):
                file_path = os.path.join(dirpath, filename)
                try:
                    os.remove(file_path)
                    print(f"[Deleted] {file_path}")
                    deleted_count += 1
                except Exception as e:
                    print(f"[Failed ] {file_path}: {e}")
    print(f"\n✅ Total .pyc files deleted: {deleted_count}")
    return deleted_count

def delete_empty_pycache_dirs(root_dir):
    removed_dirs = 0
    for dirpath, dirnames, filenames in os.walk(root_dir, topdown=False):
        if os.path.basename(dirpath) == "__pycache__" and not os.listdir(dirpath):
            try:
                os.rmdir(dirpath)
                print(f"[Removed Empty __pycache__] {dirpath}")
                removed_dirs += 1
            except Exception as e:
                print(f"[Failed to remove dir] {dirpath}: {e}")
    print(f"✅ Total empty __pycache__ folders removed: {removed_dirs}")

if __name__ == "__main__":
    import sys
    root = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.abspath(__file__))

    print(f"\n📂 Cleaning directory: {root}\n")
    delete_pyc_files(root)
    delete_empty_pycache_dirs(root)